<template>
	<view class="dk-min-area" id="dk-min-area" ref="area">
		<image :src="hotData.background" mode="aspectFill" :style="{height:height+'px',width:'100%'}" />
		<view v-for="(view, index) in views" :key="index"
			:style="{ position: 'absolute', ...view.css,background: showMask ? '#0008' : ''  }">
			<view :style="{ width: view.css.width, height: view.css.height }" class="hot-item" @click="jump(view.url)">
				<template v-if="showMask">
					{{ index + 1 }}
				</template>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'DkMinHotArea',
		props: {
			hotData: {
				type: Object,
				default: () => ({}),
			},
			showMask: {
				default: false,
				type: Boolean,
			},
		},
		data() {
			return {
				el: null,
				containerWidth: 0,
				height: 0,
				views: [],
			};
		},
		mounted() {
			this.el = this.$refs['area'];
			uni.createSelectorQuery().select('#dk-min-area').boundingClientRect((rect) => {
				this.containerWidth = rect.width;
				this.adjustHotspots();
			}).exec();

			// 监听窗口尺寸变化（全局）
			uni.onWindowResize(() => {
				uni.createSelectorQuery().select('#dk-min-area').boundingClientRect((rect) => {
					this.containerWidth = rect.width;
					this.adjustHotspots();
				}).exec();
			});
		},
		beforeDestroy() {
			// 如果有需要可以移除监听
			uni.offWindowResize(this.resizeHandler);
		},
		watch: {
			'hotData.views': {
				handler() {
					this.adjustHotspots();
				},
				deep: true,
			},
		},
		methods: {
			jump(url) {
				uni.navigateTo({
					url: url
				});
			},
			adjustHotspots() {
				this.views = JSON.parse(JSON.stringify(this.hotData.views));
				this.height = (this.containerWidth / this.hotData.width) * this.hotData.height
				this.views.forEach((view) => {
					const {
						left,
						top,
						width: originalWidth,
						height: originalHeight
					} = view.css;

					const actualWidth = Math.round(originalWidth * (this.containerWidth / this.hotData.width));
					const actualHeight = Math.round(originalHeight * (this.containerWidth / this.hotData.width));

					const actualLeft = Math.round(left * (this.containerWidth / this.hotData.width));
					const actualTop = Math.round(top * (this.containerWidth / this.hotData.width));

					view.css = {
						...view.css,
						left: actualLeft + 'px',
						top: actualTop + 'px',
						width: actualWidth + 'px',
						height: actualHeight + 'px',
					};
				});
			},
		},
	};
</script>
<style scoped>
	.dk-min-area {
		position: relative;
	}

	.hot-item {
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>